package stone926.mods.more_enchantments.items;

import net.minecraft.entity.ItemEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.Hand;
import net.minecraft.util.TypedActionResult;
import net.minecraft.world.World;
import stone926.mods.more_enchantments.damage.StoneDamageSource;
import stone926.mods.more_enchantments.util.RandomUtil;

import java.util.Random;

public class ExperienceConverterItem extends Item {

  public ExperienceConverterItem(Settings settings) {
    super(settings);
  }

  private static int getXpCost(Random random) {
    return RandomUtil.nextInt(3, 11, random);
  }

  @Override
  public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
    ItemStack stack = user.getStackInHand(hand);
    int xpCost = getXpCost(user.getRandom());
    boolean isCreative = user.isCreative();
    if (user.totalExperience > xpCost || isCreative) {
      if (!isCreative) user.addExperience(-xpCost);
      spawnExperienceBottleItem(world, user, isCreative, stack, xpCost, hand, xpCost / 2);
      return TypedActionResult.success(stack);
    } else {
      if (user.damage(StoneDamageSource.EXPERIENCE_CONVERT, xpCost)) {
        spawnExperienceBottleItem(world, user, false, stack, xpCost, hand, xpCost * 2);
        return TypedActionResult.success(stack);
      } else return TypedActionResult.fail(stack);
    }

  }

  private void spawnExperienceBottleItem(World world, PlayerEntity user, boolean isCreative, ItemStack stack, int xpCost, Hand hand, int damageAmount) {
    ItemEntity itemEntity = new ItemEntity(world, user.getX(), user.getY(), user.getZ(), new ItemStack(Items.EXPERIENCE_BOTTLE));
    itemEntity.setPickupDelay(5);
    world.spawnEntity(itemEntity);
    if (!isCreative) stack.damage(damageAmount, user, (playerEntity) -> playerEntity.sendToolBreakStatus(hand));
  }

  @Override
  public boolean hasGlint(ItemStack stack) {
    return true;
  }

}
